There are several compilations options available for Visual Basic source code and Option Explicit
defines compiler behavior for
implicit variable declarations. Specifying Option Explicit Off
will allow creating a variable by it’s first usage. This behavior can lead
to unexpected runtime errors due to typos in variable names.
Option Explicit
can be set in project properties or overridden in individual source files.
Noncompliant code example
Option Explicit Off ' Noncompliant
Module MainMod
Public Sub DoSomething(First As String, Second As String)
Parameter = Fist ' New local variable "Fist" is created and assigned to new local variable "Parameter" instead of "First" argument.
DoSomething(Parameter)
Parametr = Second ' "Second" argument is assigned to newly created variable "Parametr" instead of intended "Parameter".
DoSomething(Parameter) ' Value of "Parameter" is always Nothing
End Sub
Private Sub DoSomething(Parameter As String)
' ...
End Sub
End Module
Compliant solution
Option Explicit On
Module MainMod
Public Sub DoSomething(First As String, Second As String)
Dim Parameter As String = First
DoSomething(Parameter)
Parameter = Second
DoSomething(Parameter)
End Sub
Private Sub DoSomething(Parameter As String)
' ...
End Sub
End Module